from rest_framework import viewsets
from .models import NewsInformation
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from .serializers import NewsInformationSerializer
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

class NewsInformationViewSet(viewsets.ModelViewSet):
    """
    提供新闻信息的CRUD操作接口
    """
    queryset = NewsInformation.objects.all()
    serializer_class = NewsInformationSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['category']        # 支持 /?category=industry
    search_fields  = ['title', 'summary']  # 同时支持模糊搜索

    @action(detail=True, methods=['post'])
    def increment_click(self, request, pk=None):
        """
        每次调用该接口，对应新闻的 click 字段 +1
        """
        news = self.get_object()
        news.click += 1
        news.save()
        return Response({'click': news.click}, status=status.HTTP_200_OK)